package study.lxy.spring.springboot2.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import study.lxy.spring.springboot2.dao.UserDao;
import study.lxy.spring.springboot2.entity.LoginUser;
import study.lxy.spring.springboot2.entity.User;
import study.lxy.spring.springboot2.service.UserService;
import study.lxy.spring.springboot2.utils.JsonUtils;
import study.lxy.spring.springboot2.utils.RedisUtils;
import study.lxy.spring.springboot2.utils.consts.ErrorCode;
import study.lxy.spring.springboot2.utils.exception.BussiException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserDao userDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void createUser(User user) {
        logger.info("userServiceImpl.createUser,user={}", JsonUtils.toJsonString(user));
        if(findByName(user.getName()).size() > 0){
            logger.error("username have bean registered!");
            throw new BussiException(ErrorCode.NAME_USED);
        }
        userDao.createUser(user);
    }

    @Override
    public User queryUser(String id) {

        Cookie[] cookies = request.getCookies();
        String sessionId = "";
        for (Cookie cookie : cookies){
            logger.info("cookies,name={},value={}",cookie.getName(),cookie.getValue());
            if("SESSION_ID".equals(cookie.getName())){
                sessionId = cookie.getValue();
            }
        }
        // 获取redis中的session信息
        LoginUser loginUser = (LoginUser) redisUtils.get("SESSION_ID:" + sessionId);
        logger.info("vale from cache is {}",JsonUtils.toJsonString(loginUser));

        User user = userDao.findById(id);
        if(user == null){
            throw new BussiException(ErrorCode.USER_NOT_FUND);
        }
        return user;
    }

    @Override
    public List<User> listUser(int pageNo, int pageSize) {
        return null;
    }

    @Override
    public List<User> findByName(String name) {
        return userDao.findByName(name);
    }

    @Override
    public List<User> queryByPage(int pageNum, int pageSize) {
        int beginNum = (pageNum - 1) * pageSize ;
        return userDao.queryByPage(beginNum,pageSize);
    }
}
